<template>
	<view class="amount-operation">
		<view class="price">
			<text class="prefix font-oppo">¥</text>
			<text class="num font-oppo">
				{{ unit_price ? priceInCent(total_price) : "--" }}
			</text>
		</view>
		<view class="op">
			<image
				:src="`${imgBaseUrl}subtract-icon${amount === 1 ? '' : '-active'}.png`"
				class="img"
				@click="subtractAmount"
			/>
			<view class="amount">{{ amount }}</view>
			<image :src="`${imgBaseUrl}add-icon.png`" class="img" @click="addAmount" />
		</view>
	</view>
</template>

<script setup lang="ts">
interface AmountOperationProps {
	// 单价
	unit_price: string
}

import { ref, computed, watch } from "vue"
import { priceInCent } from "@/mixins/mixins"

const imgBaseUrl = inject("imgBaseUrl")

const props = defineProps<AmountOperationProps>()
const emit = defineEmits(["total-price-change"])
const amount = ref(1)

// 总价
const total_price = computed(() => +props.unit_price * amount.value)

const addAmount = () => {
	if (!props.unit_price) return

	amount.value += 1

	uni.$emit("amount-add")
}
const subtractAmount = () => {
	if (!props.unit_price) return
	if (amount.value === 1) return

	amount.value -= 1

	uni.$emit("amount-subtract")
}

watch(
	total_price,
	(val) => {
		emit("total-price-change", val)
	},
	{ immediate: true }
)

defineExpose({
	amount,
})
</script>

<style lang="scss" scoped>
.amount-operation {
	display: flex;
	align-items: center;
	justify-content: space-between;

	.price {
		display: flex;
		align-items: baseline;
		color: rgba(0, 0, 0, 0.9);

		.prefix {
			font-size: 24rpx;
			line-height: 32rpx;
		}

		.num {
			font-size: 36rpx;
			line-height: 32rpx;
		}
	}

	.op {
		display: flex;
		align-items: center;

		.img {
			width: 48rpx;
			height: 48rpx;
		}

		.amount {
			margin: 0 32rpx;
			font-size: 32rpx;
			color: rgba(0, 0, 0, 0.9);
			line-height: 44rpx;
		}
	}
}
</style>
